<template>
  <div class="cb-main-container">
    <div class="left">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
          </div>
        </template>
        <div class="avatar-box">
          <el-upload
              action=""
              name="file"
              :show-file-list="false"
              :accept="acceptTypes"
              :before-upload="beforeUploadAvatar"
              :http-request="uploadAvatar">
            <el-avatar :size="98" :src="user.avatar || circleUrl" />
          </el-upload>
        </div>
        <el-divider />
        <div class="item">
          <div>用户名</div>
          <div>{{ user.username }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>手机号码</div>
          <div>{{ user.phone }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>用户邮箱</div>
          <div>{{ user.email }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>部门</div>
          <div>{{ orgName }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>岗位</div>
          <div>{{ postName }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>所属角色</div>
          <div>{{ roleNames }}</div>
        </div>
        <el-divider />
        <div class="item">
          <div>创建时间</div>
          <div>{{ user.createTime }}</div>
        </div>
      </el-card>
    </div>
    <div class="right">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>基本资料</span>
          </div>
        </template>
        <el-tabs v-model="tabActiveName" class="demo-tabs">
          <el-tab-pane label="基本资料" name="first">
            <div class="form-item">
              <el-form ref="form1" :model="user" size="large" label-width="86px" :rules="rule1">
                <el-form-item prop="nickname" label="用户昵称">
                  <el-input v-model="user.nickname" maxlength="8" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item prop="phone" label="手机号">
                  <el-input v-model="user.phone" maxlength="11" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                  <el-input v-model="user.email" maxlength="64" placeholder="请输入用户邮箱" />
                </el-form-item>
                <el-form-item prop="nickname" label="性别">
                  <el-radio-group v-model="user.sex">
                    <el-radio :value="item.value" v-for="(item, itemIndex) in sexEnum" :key="itemIndex">{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="second">
            <div class="form-item">
              <el-form ref="form2" :model="model2" size="large" :rules="rule2" label-width="98px">
                <el-form-item prop="oldPassword" label="旧密码">
                  <el-input type="password" v-model="model2.oldPassword" placeholder="请输入旧密码" maxlength="32" />
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码">
                  <el-input type="password" v-model="model2.newPassword" placeholder="请输入新密码" maxlength="32" />
                </el-form-item>
                <el-form-item prop="confirmPassword" label="确认新密码">
                  <el-input type="password" v-model="model2.confirmPassword" placeholder="请输入确认新密码" maxlength="32" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>

        <el-button type="primary" @click="doSubmit">确定</el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import { detail, modifyPassword, update, uploadAvatar as uploadAvatarApi } from '@/api/system/sysUser.js'
import { isPhone, isEmail } from '@/util/ValidatorUtil.js'
import { useAdminUserStore } from '@/store/adminUser.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'SysUserProfile'
})

const sysUserStore = useAdminUserStore()
const router = useRouter()
const acceptTypes = "image/*"
const tabActiveName = ref("first")
const form1 = ref(null)
const form2 = ref(null)
const user = ref({
  id: '',
  nickname: '',
  avatar: '',
  createTime: '',
  email: '',
  orgId: '',
  organization: '',
  phone: '',
  post: '',
  postId: '',
  remark: '',
  roleIds: '',
  roles: '',
  sex: '',
  status: '',
  username: ''
})

const model2 = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const sexEnum = reactive([
  {label: '男', value: 1},
  {label: '女', value: 2}
])

const phoneValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error('手机号不能为空'))
  } else {
    if (!isPhone(value)) {
      callback(new Error('手机号格式不正确'))
    } else {
      callback()
    }
  }
}

const emailValidator = (rule, value, callback) => {
  if (!value) {
    if (!isEmail(value)) {
      callback(new Error('邮箱地址格式不正确'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const rule1 = reactive({
  'nickname': [
    {required: true, message: '昵称不能为空', trigger: 'blur'}
  ],
  'phone': [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {validator: phoneValidator, trigger: 'blur'}
  ],
  'email': [
    {validator: emailValidator, trigger: 'blur'}
  ]
})

const newPasswordValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error('新密码不能为空'))
  } else {
    if (model2.value.confirmPassword && model2.value.confirmPassword !== value) {
      callback(new Error('新密码两次输入不一致'))
    } else {
      callback()
    }
  }
}

const confirmPasswordValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error('确认密码不能为空'))
  } else {
    if (model2.value.newPassword && model2.value.newPassword !== value) {
      callback(new Error('新密码两次输入不一致'))
    } else {
      callback()
    }
  }
}

const rule2 = reactive({
  'oldPassword': [
    {required: true, message: '旧密码不能为空', trigger: 'blur'},
  ],
  'newPassword': [
    {required: true, message: '新密码不能为空', trigger: 'blur'},
    {validator: newPasswordValidator, trigger: 'blur'}
  ],
  'confirmPassword': [
    {required: true, message: '确认密码不能为空', trigger: 'blur'},
    {validator: confirmPasswordValidator, trigger: 'blur'}
  ]
})

const circleUrl = ref("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png")

const orgName = computed(() => {
  return user.value.organization ? user.value.organization.name : ''
})

const postName = computed(() => {
  return  user.value.post ? user.value.post.name : ''
})

const roleNames = computed(() => {
  let data = ''
  if(user.value.roles) {
    const roleNameArr = user.value.roles.map(role => {
      return role.name
    })
    if (roleNameArr.indexOf("超级管理员")) {
      data = '超级管理员'
    } else {
       data = roleNameArr.join(",")
    }
  }

  return data
})

const doSubmit = async () => {
  if (tabActiveName.value === 'first') {
    let valid = await form1.value.validate()
    if (valid) {
      const resp = await update(user.value)
      user.value = resp.data
    }
  } else {
    let valid = await form2.value.validate()
    if (valid) {
      await modifyPassword(model2.value)
      await sysUserStore.logout()
      router.replace({path: '/login'})
    }
  }
}

const beforeUploadAvatar = (file) => {
  const fileSize = file.size / 1024 / 1024 < 1
  if (fileSize > 1) {
    ElMessage.error('上传头像图片大小不能超过 1MB!')
    return false
  }
  return true
}

const uploadAvatar = (uploadRequestOptions) => {
  uploadAvatarApi(uploadRequestOptions.file).then(resp => {
    console.log(resp)
  })
}

onMounted(() => {
  detail().then(resp => {
    user.value = resp.data
  })
})
</script>

<style scoped lang="scss">
.cb-main-container {
  display: flex;
  flex-direction: row;

  .card-header {
    font-size: $cb-font-size-md;
  }

  .left {
    width: 480px;
    margin-right: $cb-margin-lg;

    .avatar-box {
      display: flex;
      justify-content: center;
    }

    .item {
      font-size: $cb-font-size-sm;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
  }

  .right {
    flex-grow: 2;

    .form-item {
      padding-top: $cb-padding-md;
    }
  }
}
</style>
